import axios from 'axios'
import { Message, Notification } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { baseURL } from './baseURL'
import { baseURL1 } from './baseURL'

function queryParse(query) {
  const res = []
  for (const k in query) {
    res.push(`${encodeURIComponent(k)}=${encodeURIComponent(query[k])}`)
  }
  return res.join('&')
}

// 定义请求基地址变量，测试服，旧版
// const baseURL = 'http://192.168.121.67:8110'
// const baseURL1 = 'http://192.168.121.67:8110'
// 华海联能后台
// const baseURL = 'https://www.golwayhhln.top/hhlnMes'
// 赫能士后台
// const baseURL = 'https://www.golwayhhln.top/hnsMes'

const service = axios.create({
  baseURL,
  timeout: 250 * 1000
})

// export const json2fd = json => {
//   const fd = new FormData()
//   for (let k in json) {
//     fd.append(k, json[k])
//   }
//   return fd
// }

// 请求拦截器（在请求之前进行一些配置）
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    if (config.params && config.params.isSpray || config.data && config.data.isSpray) {
      config.baseURL = baseURL1
      if (config.params) { delete config.params.isSpray }
      if (config.data) { delete config.data.isSpray }
    }
    if (config.url == '/back/processJobClass/saveProcessJobClassCodeEms' || config.url == '/device/NumericalControl/word02' || config.url == '/back/processJobClass/addTechnologyNoProcess' || config.url == '/back/money-config/verifyEquation' || config.url == '/ems-facility-maintenance/word03' || config.url == '/ems-facility-verif-test/upd' || config.url == '/device/word04' || config.url == '/device/word05' || config.url == '/back/user-knowledge-record/saveList' || config.url == '/back/user-knowledge-record/updList') {
      config.headers['Content-Type'] = 'application/json'
      config.data = JSON.stringify(config.data)
    } else {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
      config.data = queryParse(config.data)
    }
    return config
  },
  error => {
    console.log(error)
    Promise.reject(error)
  }
)

// 响应了拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    // res.code为1或者2时为正常返回
    // 此时将后台返回的主要标识数据提取出来，其中的headers，status等数据剔除
    if (res.code === 1 || res.code === 2 || res.code === 79) {
      return res
    }
    // 403表示资源不可用,拒绝访问
    else if (res.code === 403) {
      Notification({
        title: '警告',
        message: '您的登录凭证已过期，请重新登录,2秒后自动退出系统',
        type: 'warning'
      })
    } else if (res.code === 3) {
      Notification({
        title: '警告',
        message: '用户未登录',
        type: 'warning'
      })
    } else if (res.code === 21) {
      Notification({
        title: '警告',
        message: '您的权限不足',
        type: 'warning'
      })
    } else {
      Message({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000
      })
      // 暂时注释，造成影响后面代码不生效，2022-10-28 16：45
      // return Promise.reject(res)
      return res
    }
  },
  error => {
    console.log('err', error)// for debug
    Message({
      message: error.message || error.msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

// 将我们的axios实例暴露出去
export default service
